import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';

export default {
  install(Vue, options) {
    Vue.prototype.getPdf = function () {
      var title = this.pdfTitle; // 导出的pdf文件名;
      let imgHeight = window.document.getElementById(this.pdfSelector).scrollHeight // 获取DOM高度
      let imgWidth = window.document.getElementById(this.pdfSelector).scrollWidth // 获取DOM宽度

      setTimeout(() => {
        html2Canvas(document.getElementById(this.pdfSelector), { //导出的html元素
          allowTaint: true,
          useCORS: true,
          scrollX: 0,
          scrollY: 0,
          width: imgWidth,
          height: imgHeight,
        }).then(function (canvas) {

          // console.log(1);
          let contentWidth = canvas.width;
          let contentHeight = canvas.height;
          let pageHeight = contentWidth / 592.28 * 841.89;
          let leftHeight = contentHeight;
          let position = 0;
          let imgWidth = 595.28;
          let imgHeight = 592.28 / contentWidth * contentHeight;
          // 将图片转化为dataUrl,参数：图片格式和清晰度(0-1)
          // console.log(canvas.toDataURL('image/jpeg', 1.0));

          let pageData = canvas.toDataURL('image/jpeg', 1.0);
          // console.log(2);
          // let image = new Image()
          // image.src = canvas.toDataURL({
          //   format: 'image/png',
          //   quality: 1,
          //   width: 14000,
          //   height: 4000
          // })
          // var url = image.src.replace(/^data:image\/[^;]/, 'data:application/octet-stream')
          // window.open(url);

          //方向默认竖直，尺寸ponits，格式a4[595.28,841.89]
          let PDF = new JsPDF('', 'pt', 'a4');
          if (leftHeight < pageHeight) {
            //
            //addImage后两个参数控制添加图片的尺寸，此处将页面高度按照a4纸宽高比列进行压缩
            // console.log(pageData);
            PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
          } else {
            while (leftHeight > 0) {
              PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
              leftHeight -= pageHeight;
              position -= 841.89;
              if (leftHeight > 0) {
                PDF.addPage();
              }
            }
          }
          PDF.save(title + '.pdf');
          return true
        }, 1000)
      })

    }
  }
}